package com.ja.planclass.service.impl;

import com.ja.planclass.mapper.PlanClassMapper;
import com.ja.planclass.model.PlanClass;
import com.ja.planclass.model.PlanClassAddVo;
import com.ja.planclass.model.PlanClassSelectVo;
import com.ja.planclass.service.PlanClassService;
import com.ja.util.AllRecords;
import com.ja.util.ResultBuildVo;
import com.ja.util.ResultVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;

/**
 * Created by 86151 on 2019/4/22.
 */
@Service
public class PlanClassServiceImpl implements PlanClassService {
    @Autowired
    private PlanClassMapper planClassMapper;

    @Override
    @Transactional
    public ResultVo addPlanClass(PlanClassAddVo planClassAddVo) {
        PlanClass planClass = new PlanClass();
        BeanUtils.copyProperties(planClassAddVo,planClass);
        //验证计划大类编码是否已经存在
        List<PlanClass> planClasses = planClassMapper.queryPlanClassByCode(planClass.getCode());
        if (!CollectionUtils.isEmpty(planClasses)){
            return ResultBuildVo.error("已经存在此计划大类编码！","500");
        }
        //验证计划大类描述是否已经存在
        List<PlanClass> planClassByName = planClassMapper.queryPlanClassByName(planClass.getCode());
        if (!CollectionUtils.isEmpty(planClassByName)){
            return ResultBuildVo.error("已经存在此计划大类名称！","500");
        }
        planClass.setCreateName("小明");
        planClass.setCreateTime(new Date());
        planClassMapper.addPlanClass(planClass);
        return ResultBuildVo.success(planClassAddVo);
    }

    @Override
    public ResultVo<AllRecords> queryPage(PlanClassSelectVo planClassSelectVo) {
        //1查询数据库条数
        int count = planClassMapper.queryCount(planClassSelectVo);
        //2.查询数据库数据
        List<PlanClass> planClasses = planClassMapper.queryPage(planClassSelectVo);
        //3.new AllRecords给allRecordes赋值
        AllRecords allRecords = new AllRecords();
        allRecords.setTotalNumber(count);
        allRecords.setPageSize(planClassSelectVo.getPageSize());
        allRecords.setPageIndex(planClassSelectVo.getPageIndex());
        allRecords.setDataList(planClasses);
        allRecords.resetTotalNumber(count);
        //4.返回allRecordes
        return ResultBuildVo.success(allRecords);
    }
}
